package www.dashu.com.service;

import www.dashu.com.constant.AuthConstant;
import www.dashu.com.dao.SysPermissionDao;
import www.dashu.com.domain.SysPermission;
import www.dashu.com.domain.SysRole;
import www.dashu.com.domain.SysRolePerms;
import www.dashu.com.service.base.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SysPermissionService extends BaseService<SysPermission,Long, SysPermissionDao>{

    @Autowired
    SysRoleService roleService;
    @Autowired
    SysRolePermsService rolePermsService;
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

//    @Async("taskExecutor")
    public Map<String, List<String>> initResourceRolesMap() {
        Map<String,List<String>> resourceRoleMap = new TreeMap<>();
        List<SysPermission> resourceList = getPermisstions();
        List<SysRole> roleList = roleService.findAll();
        List<SysRolePerms> relationList = rolePermsService.findAll();
        for (SysPermission resource : resourceList) {
            Set<Long> roleIds = relationList.stream().filter(item -> item.getPId().equals(resource.getId())).map(SysRolePerms::getRId).collect(Collectors.toSet());
            List<String> roleNames = roleList.stream().filter(item -> roleIds.contains(item.getId())).map(item -> item.getId() + "_" + item.getName()).collect(Collectors.toList());
            resourceRoleMap.put("/"+resource.getUrl(),roleNames);
        }
        redisService.del(AuthConstant.RESOURCE_ROLES_MAP_KEY);
        redisService.hSetAll(AuthConstant.RESOURCE_ROLES_MAP_KEY, resourceRoleMap);
        return resourceRoleMap;
    }

    public List<SysPermission> getPermisstions(){
        Map<String, Object> queryMaps = new HashMap<>();
        queryMaps.put("type","1");
        return this.findAll(queryMaps);
    }

    @Async("taskExecutor")
    public void initTableIds() {
        List<Map<String,String>> tables = roleService.findAllTables();
        tables.forEach(mapItem -> {
            String key = "ids:"+mapItem.get("name");
            Object initValue = redisTemplate.opsForValue().get(key);
            if(null == initValue || 0l == Long.parseLong(initValue.toString())){
                redisTemplate.opsForValue().set(key,3000200l);
            }
        });
    }

    public List<SysPermission> findAllSort(){
        return dao.findAllSort();
    }

}